package com.situ.web.controller;

import com.situ.web.pojo.User;
import com.situ.web.pojo.query.UserQuery;
import com.situ.web.service.IUserService;
import com.situ.web.service.impl.UserServiceImpl;
import com.situ.web.util.JSONResult;
import com.situ.web.util.JSONUtil;
import com.situ.web.util.LayUITableJSONResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

// /user?method=selectByPage&pageNo=2
@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private IUserService userService = new UserServiceImpl();

    // /user?method=deleteById&id=2
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method == null || method.equals("")) {
            method = "selectByPage";
        }
        switch (method) {
            case "selectByPage":
                selectByPage(req, resp);
                break;
            case "login":
                login(req, resp);
                break;
            case "logout":
                logout(req, resp);
            case "deleteById":
                deleteById(req, resp);
                break;
            case "deleteAll":
                deleteAll(req, resp);
                break;
            case "add":
                add(req, resp);
                break;
            case "getUserUpdatePage":
                getUserUpdatePage(req, resp);
                break;
            case "update":
                update(req, resp);
                break;
        }
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.update");
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String age = req.getParameter("age");
        String address = req.getParameter("address");
        User user = new User(Integer.parseInt(id), name, password, Integer.parseInt(age), address);
        JSONResult jsonResult = userService.update(user);
        JSONUtil.obj2Json(jsonResult, resp);
    }

    private void getUserUpdatePage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("UserServlet.getUserUpdatePage");
        String id = req.getParameter("id");
        User user = userService.selectById(Integer.parseInt(id));
        req.setAttribute("user", user);
        req.getRequestDispatcher("user_update.jsp").forward(req, resp);
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.add");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String age = req.getParameter("age");
        String address = req.getParameter("address");
        User user = new User(name, password, Integer.parseInt(age), address);
        JSONResult jsonResult = userService.add(user);
        JSONUtil.obj2Json(jsonResult, resp);
    }

    private void deleteAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.deleteAll");
//        String ids = req.getParameter("ids");// "4,6"
//        String[] idArray = ids.split(",");
        String[] ids = req.getParameterValues("ids[]");
        JSONResult jsonResult = userService.deleteAll(ids);
        JSONUtil.obj2Json(jsonResult, resp);
    }

    private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.deleteById");
        String id = req.getParameter("id");
        JSONResult jsonResult = userService.deleleById(Integer.parseInt(id));
        JSONUtil.obj2Json(jsonResult, resp);
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        session.invalidate();
        resp.sendRedirect(req.getContextPath() + "/login.jsp");
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 先判断验证码是不是正确
        // 验证码错误，返回一个错误提示信息
        // 验证码正确，再验证用户名和密码是否正确
        String code = req.getParameter("code");
        HttpSession session = req.getSession();
        String codeInSession = (String) session.getAttribute("codeInSession");
        if (!codeInSession.equalsIgnoreCase(code)) {
            // 请求是成功还是失败：ok error
            // 后台希望前台弹出消息：msg
            // 后台返回前台数据：Data
            /*JSONResult jsonResult = new JSONResult();
            jsonResult.setCode(1);
            jsonResult.setMsg("验证码错误");*/

            JSONUtil.obj2Json(JSONResult.error("验证码错误"), resp);
            return;
        }

        String name = req.getParameter("name");
        String password = req.getParameter("password");
        User user = userService.login(name, password);
        if (user == null) {
            JSONUtil.obj2Json(JSONResult.error("用户名密码错误"), resp);
        } else {
            //登录上之后，将登录的凭证user对象放到这个用户的Session中
            session.setAttribute("user", user);
            JSONUtil.obj2Json(JSONResult.ok("登录成功"), resp);
        }
    }

    private void login1(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        User user = userService.login(name, password);
        if (user == null) {
            resp.sendRedirect(req.getContextPath() + "/fail.jsp");
        } else {
            //登录上之后，将登录的凭证user对象放到这个用户的Session中
            HttpSession session = req.getSession();
            session.setAttribute("user", user);
            resp.sendRedirect(req.getContextPath() + "/");
        }
    }

    // /user?method=selectByPage&pageNo=2&pageSize=5
    // /user?method=selectByPage&page=2&limit=5
    private void selectByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("UserServlet.selectByPage");
        String page = req.getParameter("page");
        if (page == null || page.equals("")) {
            page  = "1";
        }
        String limit = req.getParameter("limit");
        if (limit == null || limit.equals("")) {
            limit = "5";
        }
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        //http://localhost:8080/JavaWeb/user?method=selectByPage&page=1&limit=10&name=aa&age=23
        UserQuery userQuery = new UserQuery(Integer.parseInt(page), Integer.parseInt(limit), name, age);

        //PageInfo pageInfo = userService.selectByPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        LayUITableJSONResult layUITableJSONResult = userService.selectByPage(userQuery);

        JSONUtil.obj2Json(layUITableJSONResult, resp);
    }
}
